package projectsupporter.common.logic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import dbTools.DBToolEngine;
import dbTools.XML.CommonXMLReader;
import dbTools.XML.CommonXmlCreator;
import dbTools.tableInfo.info.TableInfo;
import dbTools.util.FileUtil;

public class PlugLogic {


	public static List<String> BASE_CODE_COPY_LIST = new ArrayList<String>(){{
		   add(DBToolEngine.getWorkSpacePath()+GlobalInfo.BASE_ID+"/WebRoot");
		   add(DBToolEngine.getWorkSpacePath()+GlobalInfo.BASE_ID+"/src/jp/co/sn/system");
		   add(DBToolEngine.getWorkSpacePath()+GlobalInfo.BASE_ID+"/src/template");
		   add(DBToolEngine.getWorkSpacePath()+GlobalInfo.BASE_ID+"/config");
	    }};
	    
	    
//	public static void copyBaseCode(String toPrjName) {
//		System.out.println("copy begin!");
//
//		for (String path : BASE_CODE_COPY_LIST) {
//			PlugLogic.copyFolder(path, path.replace(GlobalInfo.BASE_ID,toPrjName));
//		}
//
//		System.out.println("copy end!");
//	}
 
	public static String[] getConnectInfo()
	{
		// TODO change the return type to a connect obj
		String[] infos=new String[3];
		
		if(GlobalInfo.DBConfigFileName==null)
		{
			return null;
		}
		
		try {
			Document doc =CommonXMLReader.load(GlobalInfo.DBConfigFileName
					,DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath);
			
			Element root = doc.getRootElement();
			//dataSource
			Element ds = (Element)root.elements().get(0);
			
			//url
			Element url=(Element)((Element)ds.elements().get(1)).elements().get(0);
			
			//username
			Element userName=(Element)((Element)ds.elements().get(2)).elements().get(0);
			
			//password
			Element password=(Element)((Element)ds.elements().get(3)).elements().get(0);
			
			infos=new String[]{url.getText(),userName.getText(),password.getText()};
		} catch (Exception e) {
			return null;
		}
		
		return infos;
	}
	
	public static void saveConnectInfo(String[] info)
	{
		if(GlobalInfo.DBConfigFileName==null)
		{
			return ;
		}
		
		try {
			Document doc =CommonXMLReader.load(GlobalInfo.DBConfigFileName
					,DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath);
			
			Element root = doc.getRootElement();
			//dataSource
			Element ds = (Element)root.elements().get(0);
			
			//url
			Element url=(Element)((Element)ds.elements().get(1)).elements().get(0);
			
			//username
			Element userName=(Element)((Element)ds.elements().get(2)).elements().get(0);
			
			//password
			Element password=(Element)((Element)ds.elements().get(3)).elements().get(0);
			
			url.setText(info[0]);
			userName.setText(info[1]);
			password.setText(info[2]);
			
			CommonXmlCreator.createXML(doc,
					DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath,
					GlobalInfo.DBConfigFileName);
			
		} catch (Exception e) {
			return ;
		}
	}
	
	public static void addMappingResources(List<String> mappingFilesPath)
	{
		if(GlobalInfo.DBConfigFileName==null)
		{
			return ;
		}
		
		try {
			Document doc =CommonXMLReader.load(GlobalInfo.DBConfigFileName
					,DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath);
			
			Element root = doc.getRootElement();

			Element sessionFactory = (Element)root.elements().get(2);
			Element mapList=(Element)((Element)sessionFactory.elements().get(2)).elements().get(0);

			mapList.clearContent();
			for(String filePath : mappingFilesPath)
			{
				Element value=mapList.addElement("value");
				value.setText(filePath);
			}
			
			CommonXmlCreator.createXML(doc,
					DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath,
					GlobalInfo.DBConfigFileName);
			
		} catch (Exception e) {
			return ;
		}
	}
	
	/* 复制整个文件夹内容   
	 *    
	 * @param oldPath   
	 *            String 原文件路径 如：c:/old 
	 * @param newPath   
	 *            String 复制后路径 如：f:/new 
	 * @return boolean   
	 */    
	public static void copyFolder(String oldPath, String newPath) {     
	    
	    try {     
	        (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹     
	        File a = new File(oldPath);     
	        String[] file = a.list();     
	        File temp = null;     
	        for (int i = 0; i < file.length; i++) {     
	            if (oldPath.endsWith(File.separator)) {     
	                temp = new File(oldPath + file[i]);     
	            } else {     
	                temp = new File(oldPath + File.separator + file[i]);     
	            }     
	            if (temp.isFile()&& temp.isHidden()==false) {     
	                FileInputStream input = new FileInputStream(temp);     
	                FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());     
	                byte[] b = new byte[1024 * 5];     
	                int len;     
	                while ((len = input.read(b)) != -1) {     
	                    output.write(b, 0, len);     
	                }     
	                output.flush();     
	                output.close();     
	                input.close();     
	            }     
	            if (temp.isDirectory() && temp.isHidden()==false && !temp.getName().equals("test")) {// 如果是子文件夹     
	                copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);     
	            }     
	        }     
	    } catch (Exception e) {     
	        System.out.println("复制整个文件夹内容操作出错");     
	        e.printStackTrace();     
	    }     
	}

	public static void addPojoClassConfig(Map<String, String> pojoClassMap) {
	
		FileUtil file= new FileUtil(DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.pojoClassMapFilePath,GlobalInfo.pojoClassMapName);
		file.replaceTxtByStr(GlobalInfo.pojoClassMapModelStr, getpojoClassconfig(pojoClassMap));
		
		FileUtil file2= new FileUtil(DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath,GlobalInfo.DBServiceFileName);
		file2.replaceTxtByStr("zousin", GlobalInfo.PRJ_NAME.toLowerCase());
		
		FileUtil file3= new FileUtil(DBToolEngine.getWorkSpacePath()+GlobalInfo.PRJ_NAME+ GlobalInfo.DBConfigFilePath,GlobalInfo.DBPOJOFileName);
		file3.replaceTxtByStr("<!--##POJO beans##-->", getpojoBeanconfig(pojoClassMap));
	}    
	private static String getpojoClassconfig(Map<String, String> pojoClassMap)
	{
		StringBuffer str=new StringBuffer();
		for(Map.Entry<String,String> entry : pojoClassMap.entrySet())
		{
			str.append("POJO_CLASSES.put(\""+entry.getKey()+"\", "+entry.getValue()+".class);"+"\r\n		");
		}
		return str.toString();
	}
	
	private static String getpojoBeanconfig(Map<String, String> pojoClassMap)
	{
		StringBuffer str=new StringBuffer();
		for(Map.Entry<String,String> entry : pojoClassMap.entrySet())
		{
			str.append("<bean id=\""+entry.getKey()+"\" scope=\"request\"  class=\""+entry.getValue()+"\"></bean>\r\n		");	
		}
		return str.toString();
	}
}
